package com.luyu.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

// 处理oauth2获取授权或者token的过滤器
public class LoginClientFilter extends OncePerRequestFilter {

    private RequestMatcher requestMatcher;

    private AuthenticationConverter converter;

    private AuthenticationManager authenticationManager;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (!requestMatcher.matches(request)){
            filterChain.doFilter(request,response);
            return;
        }
        Authentication authentication = converter.convert(request);
        Authentication authenticate = authenticationManager.authenticate(authentication);
        if (!authenticate.isAuthenticated()) {
            filterChain.doFilter(request,response);
            return;
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request,response);
        return;
    }




}
